<?php

namespace app\mini\controller;

use app\company\model\CompanyGoodsRule;
use app\mini\validate\StoreCartValidate;
use app\service\traits\Crud;
use app\mini\model\StoreCart as StoreCartModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Response;

class StoreCart extends Base
{
    private StoreCartModel $model;

    private bool $isSalesman = false;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new StoreCartModel();
        $this->validateClass = StoreCartValidate::class;
        $this->isSalesman  = $this->userInfo->is_salesman == 1 ?? false;
    }


    /**
     * 列表
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Response
    {
        $param = request()->param();
        // validate($this->validateClass)->scene('list')->check($param);
        $sql   = $this->model->where('store_user_id', $this->user_id);
        $count = $sql->count();
        $sql   = $sql->page($param['page'], $param['limit']);
        $list  = $sql->order('create_time desc')->select()->each(function ($item) {
            $item->goods_rule = $item->goodsRule()->withTrashed()->field('money,spec_name,img')->find();
            $item->goods      = $item->goods()->withTrashed()->field('id,name,img')->find();
        });
        return $this->success('操作成功', compact('list', 'count'));
    }

    /**
     * 业务员购物车列表
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function salesmanList(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene('list')->check($param);
        $list = $this->model->where('store_user_id', $this->user_id)
                            ->where('store_id', $param['store_id'])
                            ->field('store_id')
                            ->order('id desc')
                            ->group('store_id')
                            ->select()
                            ->each(function ($item) {
                                $item->store_name = $item->store()->value('name');
                                $item->list = $this->model
                                    ->where('store_user_id', $this->user_id)
                                    ->where('store_id', $item->store_id)
                                    ->select()->each(function ($vo) {
                                        $vo->goods_rule = $vo->goodsRule()->withTrashed()->field('money,spec_name,img')->find();
                                        $vo->goods      = $vo->goods()->withTrashed()->field('id,name,img')->find();
                                    });
                            })->toArray();
        return $this->success('操作成功', $list);
    }

    /**
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function add(): Response
    {
        $param = request()->param();
//        $this->company_id = $this->userInfo->company_id;
        validate($this->validateClass)->scene('add')->check($param);
        //校验商品是否存在
        if (!$rule = CompanyGoodsRule::where('goods_rule_id', $param['goods_rule_id'])->gs()->status(1)->find())
        {
            return $this->error('商品不存在或已下架');
        }

        $model = $this->model->where('store_user_id', $this->user_id)->where('goods_rule_id', $param['goods_rule_id']);
        if ($this->isSalesman) $model = $model->where('store_id',$param['store_id']);
        $model = $model->find();

        //todo 购物车要不要存放单价,如果价格变更.....
        if ($model) {
            //is_input == 1 代表增加/减少  == 2 代表重置
            if (request()->param('is_input') == 1) {
                if ($model->quantity + $param['quantity'] > 0) {
                    $model->inc('quantity', $param['quantity'])->inc('amount', $model->money * $param['quantity'])->save();
                }else if ($model->quantity + $param['quantity'] <= 0) {
                    //当数量为0时删除
                    $quantity = -$model->quantity;
                    $model->inc('quantity', -$model->quantity)->inc('amount', $model->money * $quantity)->save();
                    $model->force()->delete();
                }
            }
            if (request()->param('is_input') == 2) {
                $model->quantity = $param['quantity'];
                $model->amount   = $model->money * $param['quantity'];
                $model->save();
            }
        } else {
            if($param['quantity'] <= 0) return $this->error('数量必须大于0');
            $param['goods_id']      = $rule->goods_id;
            $param['money']         = $rule->money;
            $param['img']           = $rule->img;
            $param['store_user_id'] = $this->user_id;
            $param['amount']        = $rule->money * $param['quantity'];
            $this->model->save($param);
        }
        return $this->success('操作成功');
    }

}